/**
 * @项目名称: shaoshaohuo 
 * @文件名称: IMActivity.java 
 * @Date: 2015年12月7日 
 * @Copyright: 2015 www.longinf.com Inc. All rights reserved. 
 * 注意：本内容仅限于北京龙息科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.shaoshaohuo.app.utils.im;

import android.content.Context;
import android.content.Intent;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.conversation.EServiceContact;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.SshApplication;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.net.HttpConfig;

/**
 * IM即时通讯入口
 * @Project: shaoshaohuo 
 * @Author: Osborn 
 * @Date: 2015年12月7日 
 * @Copyright: 2015 www.tianmaoetong.com Inc. All rights reserved.
 */
public class IMFactory {
	
	/**
	 *IM用户ID的前缀 
	 */
	public static String USER_ID_PREFIX;
	static {
		switch (HttpConfig.serverEnvironment) {
        case DEVELOPMENT:
        	USER_ID_PREFIX = "";
            break;
        case TEST:
        	USER_ID_PREFIX = "tmet_test_";
            break;
		case PRE_PUBLISH:
        	USER_ID_PREFIX = "tmet_test_";
            break;
        case ONLINE:
        	USER_ID_PREFIX = "tmet_";
            break;
        }
	}
	
	public static final String SERVICE_CONSTACT = "田贸e通01";
	
	public static String default_userid = "tmet_01";
	public static String default_password = "tmet727";
	public static String targetUserId = "tmet_02";
	
	public static String userid;
	public static String password;
	private static YWIMKit imkit;
	private static boolean isLogined;
	private static final int MAX_LOGIN_TRY = 10;//最大尝试登录次数
	private static int haveTriedTimes = 0; //计录本次会话已尝试登录的次数
	
	public static void init() {
		imkit = YWAPI.getIMKitInstance();
		//自定义消息通知栏的显示
		imkit.setEnableNotification(true);//开启通知栏提示
		imkit.setAppName(SshApplication.getContext().getString(R.string.app_name));//通知栏显示的名称
		imkit.setResId(R.drawable.logo);//开发者可以换成自定义的Icon
		Intent intent = imkit.getConversationActivityIntent(); //开发者可以使用openIM提供的intent也可以使用自定义的intent
		imkit.setNotificationIntent(intent); //通知栏点击跳转，同时也支持针对单个会话的消息提醒与否的设置（免打扰）
	}
	
	
	/**
	 * 登录，最好是在最开始登录一次
	 * @param userid
	 * @param password
	 * @param userCallback		可为空
	 */
	public static void login(final String userid, final String password, final IWxCallback userCallback ) {
		IMFactory.userid = userid;
		IMFactory.password = password;
		if (isLogined) {
			return;
		}
		if (imkit == null) {
			return;
		}
		
		//创建登录对象
		YWLoginParam loginParam = YWLoginParam.createLoginParam(userid, password);
		//获取登录服务
		IYWLoginService loginService = imkit.getLoginService();
		loginService.login(loginParam, new IWxCallback() {
			 
		    @Override
		    public void onSuccess(Object... arg0) {
		    	isLogined = true;
		    	haveTriedTimes = 0;
		    	if (userCallback != null) {
		    		userCallback.onSuccess(arg0);
		    	}
		    }
		 
		    @Override
		    public void onProgress(int arg0) {
		    	if (userCallback != null) {
		    		userCallback.onProgress(arg0);
		    	}
		    }
		 
		    @Override
		    public void onError(int errCode, String description) {
		        //如果登录失败，errCode为错误码,description是错误的具体描述信息
		    	LogUtil.e(getClass().getSimpleName(), "errCode:" + errCode + " description:" + description);
				//当前登录userId：tmet_885 与之前登录的userId： tmet_test_575 不一致，应该首先调用logout
				if (errCode == -4) {
					logout();
				}
		    	if (userCallback != null) {
		    		userCallback.onError(errCode, description);
		    	}
		    	haveTriedTimes++;
		    	if (haveTriedTimes < MAX_LOGIN_TRY) {
		    		login(userid, password, null);
		    	}
		    }
		});
	}
	
	/**
	 * 获取IM用户的ID
	 * @param userId
	 * @return
	 */
	public static String getImId(String userId) {
		return USER_ID_PREFIX + userId;
	}
	
	/**
	 * 打开面面聊天窗口
	 * @param activity
	 * @param targetUserId
	 */
	public static void openChat(final Context activity, final String targetUserId) {
		if (isLogined) {
			Intent intent = imkit.getChattingActivityIntent(IMFactory.getImId(targetUserId));
			activity.startActivity(intent);
		} else {
			IMFactory.login(AccountManager.getUserId(), IMFactory.default_password, new IWxCallback() {

				@Override
				public void onError(int arg0, String arg1) {

				}

				@Override
				public void onProgress(int arg0) {

				}

				@Override
				public void onSuccess(Object... arg0) {
					if (imkit == null) {
						return;
					}
					Intent intent = imkit.getChattingActivityIntent(IMFactory.getImId(targetUserId));
					activity.startActivity(intent);
				}

			});
		}
	}
	
	/**
	 * 打开客服聊天
	 * @param activity
	 */
	public static void openChatServiceContact(final Context activity) {
		if (isLogined) {
			EServiceContact contact = new EServiceContact(SERVICE_CONSTACT, 0);
			Intent intent = imkit.getChattingActivityIntent(contact);
			activity.startActivity(intent);
		} else {
			IMFactory.login(IMFactory.getImId(AccountManager.getUserId()), IMFactory.default_password, new IWxCallback() {

				@Override
				public void onError(int arg0, String arg1) {

				}

				@Override
				public void onProgress(int arg0) {

				}

				@Override
				public void onSuccess(Object... arg0) {
					if (imkit == null) {
						return;
					}
					EServiceContact contact = new EServiceContact(SERVICE_CONSTACT, 0);
					Intent intent = imkit.getChattingActivityIntent(contact);
					activity.startActivity(intent);
				}

			});
		}
	}
	
	/**
	 * 打开聊天列表
	 * @param activity
	 */
	public static void openConversation(final Context activity) {
		if (isLogined) {
			Intent intent = imkit.getConversationActivityIntent();
			activity.startActivity(intent);
		} else {
			IMFactory.login(IMFactory.getImId(AccountManager.getUserId()), IMFactory.default_password, new IWxCallback() {

				@Override
				public void onError(int arg0, String arg1) {

				}

				@Override
				public void onProgress(int arg0) {

				}

				@Override
				public void onSuccess(Object... arg0) {
					if (imkit == null) {
						return;
					}
					Intent intent = imkit.getConversationActivityIntent();
					activity.startActivity(intent);
				}

			});
		}
	}
	
	public static void logout() {
		if (isLogined) {
			//获取登录服务
			IYWLoginService loginService = imkit.getLoginService();
			loginService.logout(new IWxCallback() {
				
				@Override
				public void onSuccess(Object... arg0) {
					LogUtil.i(getClass().getSimpleName(), "阿里IM退出登录  Success");
					isLogined = false;
				}
				
				@Override
				public void onProgress(int arg0) {
					
				}
				
				@Override
				public void onError(int arg0, String arg1) {
					LogUtil.e(getClass().getSimpleName(), "阿里IM退出登录    Failure");
				}
			});
		}
	}
	
	
	/**
	 * 获取未读取信息数
	 * @return
	 */
	public static int getUnreadCount() {
		if (imkit != null) {
			return imkit.getUnreadCount();
		}
		return 0;
	}
}
